import Taro from '@tarojs/taro'
import { action, observable } from 'mobx'

// apis
import * as shopAddressesApi from '../../../apis/shopAddressesApi'

// models
import ShopAddresses from '../../../models/ShopAddresses'

// store
import addressListStore from '../list/store'

class AddressDetailStore {
  @observable
  editAddress?: ShopAddresses
  @observable
  name: string = ''
  @observable
  mobile: string = ''
  @observable
  region: string[] = []
  @observable
  address: string = ''
  @observable
  street: string = ''
  @observable
  isDefault: boolean = true

  @action
  async init({ address }: { address?: ShopAddresses }) {
    this.editAddress = address
    if (address) {
      this.name = address.consignee
      this.mobile = address.mobile
      this.region = [address.provinceName, address.cityName, address.districtnName]
      this.address = address.address
      this.isDefault = address.isDefault === 1 ? true : false
    } else {
      this.name = ''
      this.mobile = ''
      this.region = []
      this.address = ''
      this.isDefault = true
    }
  }

  @action
  changeName = (value: string) => {
    this.name = value
  }
  @action
  changeMobile = (value: string) => {
    this.mobile = value
  }
  @action
  changeRegion = (value: string[]) => {
    this.region = value
  }
  @action
  changeStreet = (value: string) => {
    this.street = value
  }
  @action
  changeAddress = (value: string) => {
    this.address = value
  }
  @action
  toggleIsDefault = () => {
    this.isDefault = !this.isDefault
  }
  @action
  save = async () => {
    // TODO 校验参数
    const provinceName = this.region[0]
    const cityName = this.region[1]
    const districtnName = this.region[2]

    if (!this.name || !this.name.trim()) {
      Taro.showToast({ title: '请输入姓名', icon: 'none' })
      return
    }

    if (this.name.length > 8) {
      Taro.showToast({ title: '姓名不能超过8个字', icon: 'none' })
      return
    }

    if (!provinceName || !cityName || !districtnName) {
      Taro.showToast({ title: '请选择城市地区', icon: 'none' })
      return
    }
    if (!this.address || !this.address.trim()) {
      Taro.showToast({ title: '请输入详细地址', icon: 'none' })
      return
    }

    Taro.showLoading({ title: '保存中...' })

    await shopAddressesApi.addOrUpdate({
      uid: 1, // 用户，TODO
      id: this.editAddress ? this.editAddress.id : undefined,
      isDefault: this.isDefault ? 1 : 0,
      consignee: this.name,
      mobile: this.mobile,
      provinceName,
      cityName,
      districtnName,
      streetName: this.street,
      address: this.address
    })

    Taro.hideLoading()
    Taro.navigateBack()
    addressListStore.init()
  }
}

export default new AddressDetailStore()
